<template>
  <div>
    <el-card>
      <el-button
        type="primary"
        icon="Plus"
        @click="addTradeMark"
        v-has="`btn.Trademark.add`"
      >
        添加品牌
      </el-button>
      <el-table :data="tableData" border style="width: 100%; margin-top: 5px">
        <el-table-column
          fixed
          type="index"
          :index="1"
          label="序号"
          width="150"
          align="center"
        />
        <el-table-column prop="tmName" label="品牌名称" />
        <el-table-column label="品牌Logo" align="center">
          <template #default="{ row }">
            <img
              :src="row.logoUrl"
              :alt="row.tmName"
              style="width: 50px; height: 50px"
            />
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              icon="Delete"
              @click="DeleteTradeMark(row)"
              v-has="`btn.Trademark.remove`"
            >
              删除
            </el-button>
            <el-button
              type="primary"
              size="small"
              icon="Edit"
              @click="EditTradeMark(row)"
              v-has="`btn.Trademark.update`"
            >
              修改
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器组件属性
       v-model:current-page当前页码
       v-model:page-size每页多少条数据
       :page-size每页多少条数据选择器
       :small样式大小默认false
       :background背景颜色
       layout:设置分页器组件排列顺序
       total共多少条数据,
       size每页展示多少，
       prev上一页，
       paper连续页码组件，
       next下一页，
       jumper自选页码跳转
     -->
      <div class="demo-pagination-block">
        <el-pagination
          background
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 2, 3, 4]"
          layout="prev, pager, next,jumper, ->,sizes,total"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 对话框组件实现添加与修改已有品牌的业务 -->
    <!-- v-model="dialogFormVisible"用于控制显示隐藏 
    title设置左上角标题-->
    <div>
      <el-dialog
        v-model="dialogFormVisible"
        :title="dialogtitle"
        @closed="closeDialog"
        :destroy-on-close="true"
      >
        <el-form
          style="width: 80%"
          :model="trademarkParams"
          :rules="rule"
          status-icon
          ref="formRef"
        >
          <el-form-item label="品牌名称" label-width="80px" prop="tmName">
            <el-input
              v-model="trademarkParams.tmName"
              placeholder="请输入品牌名称"
            />
          </el-form-item>
          <el-form-item label="品牌LOGO" label-width="80px" prop="logoUrl">
            <!-- action是图片上传地址,需要带api前缀经过代理服务器发送请求 -->
            <el-upload
              class="avatar-uploader"
              action="/api/admin/product/fileUpload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="trademarkParams.logoUrl"
                :src="trademarkParams.logoUrl"
                class="avatar"
              />
              <el-icon v-else class="avatar-uploader-icon"><Picture /></el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button
              type="primary"
              size="default"
              @click="dialogFormVisible = false"
            >
              取消
            </el-button>
            <el-button type="primary" size="default" @click="confirm">
              确定
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script lang="ts" setup name="index">
import { ref, onMounted, reactive } from 'vue'
// 导入接口
import {
  reqHasTrademark,
  reqAddOrUpdateTrademark,
  reqDeleteTradeMark,
} from '@/api/product/trademark/index'
//导入类型接口
import { Records, TradeMark } from '@/api/product/trademark/type'
//导入upload类型从element
import { ElMessage, type UploadProps, ElMessageBox } from 'element-plus'
//table数据源
let tableData = ref<Records>([])
//当前页码
let currentPage = ref<number>(1)
//每页多少条数据
let pageSize = ref<number>(10)
//一共多少条数据
let total = ref<number>(0)
//控制dialog对话框显示销毁
let dialogFormVisible = ref(false)
// 定义添加新品牌的参数项
let trademarkParams = reactive<TradeMark>({
  tmName: '',
  logoUrl: '',
})
//dialog标题
let dialogtitle = ref<string>('')
//定义表单校验规则，表单中含有图片。在信息提交里面使用ref获取表单实例中的validate回调函数对整个表单校验
let formRef = ref()
//--------------------------------------方法-------------------------------------------------------
// 获取数据封装成方法函数
const HasTrademark = async () => {
  let { data: result } = await reqHasTrademark(
    currentPage.value,
    pageSize.value,
  )
  total.value = result.total
  tableData.value = result.records
}
//渲染完请求数据的钩子
onMounted(() => {
  HasTrademark()
})
//每页显示多少条数据发生改变时会自己传过来每页多少条
let handleSizeChange = (size: number) => {
  pageSize.value = size
  HasTrademark()
}
//当前页码发生改变，自己传过来参数就是当前页码
let handleCurrentChange = (current: number) => {
  currentPage.value = current
  HasTrademark()
}
//dialog关闭时的回调函数，来清空表单中的数据
const closeDialog = () => {
  ;(trademarkParams.tmName = ''), (trademarkParams.logoUrl = '')
}
//添加显示对话框
const addTradeMark = () => {
  dialogFormVisible.value = true
  dialogtitle.value = '添加品牌'
}
//删除
const DeleteTradeMark = (row: TradeMark) => {
  ElMessageBox.confirm(`你正在删除品牌"${row.tmName}". 继续?`, '注意', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      await reqDeleteTradeMark(row.id)
        .then((result) => {
          if (result.code == 200) {
            HasTrademark()
            ElMessage({
              type: 'success',
              message: '删除成功',
            })
          } else {
            ElMessage({
              type: 'error',
              message: result.message,
            })
          }
        })
        .catch((error) => {
          ElMessage({
            type: 'error',
            message: '删除失败' + error,
          })
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
//编辑显示对话框
const EditTradeMark = (row: TradeMark) => {
  dialogtitle.value = '修改品牌'
  dialogFormVisible.value = true
  trademarkParams.id = row.id
  trademarkParams.tmName = row.tmName
  trademarkParams.logoUrl = row.logoUrl
}
//beforeAvatarUpload,上传文件之前的校验
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  //上传文件之前约束文件大小等操作限制文件类型
  if (
    rawFile.type == 'image/png' ||
    rawFile.type == 'image/jpeg' ||
    rawFile.type == 'image/gif'
  ) {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true
    } else {
      ElMessage({
        type: 'error',
        message: '图片大小不能超过4MB',
      })
      return false
    }
  } else {
    ElMessage({
      type: 'error',
      message: '上传文件类型必须是png/jpg/gif',
    })
    return false
  }
}
const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
  //response上传成功后返回code，data文件路径，message，oktrue
  trademarkParams.logoUrl = response.data
  //图片上传成功后清除表单验证提示
  formRef.value.clearValidate('logoUrl')
}
//添加品牌/修改品牌
const confirm = async () => {
  //表单校验成功后继续添加，失败了就堵塞
  try {
    await formRef.value.validate()
    let result = await reqAddOrUpdateTrademark(trademarkParams)
    if (result.code == 200) {
      dialogFormVisible.value = false
      HasTrademark()
      ElMessage({
        type: 'success',
        message: trademarkParams.id
          ? `成功修改品牌${trademarkParams.tmName}`
          : `新增品牌${trademarkParams.tmName}`,
      })
    } else {
      dialogFormVisible.value = false
      HasTrademark()
      ElMessage({
        type: 'error',
        message: trademarkParams.id
          ? `修改品牌${trademarkParams.tmName}失败`
          : `新增品牌${trademarkParams.tmName}失败`,
      })
    }
  } catch (error) {
    ElMessage({
      type: 'error',
      message: '信息不合法',
    })
  }
}
//自定义校验方法
const validaTname = (rule: any, value: any, callback: any) => {
  const special = /[`~!@#$%^&*()_+<>?:"{},.\/;'[\]]/im.test(value)
  //大于两个字符并且不包含特殊字符
  if (value.trim().length >= 2 && !special) {
    callback()
  } else {
    callback(new Error('品牌名称长度大于等于两个字符,且不能包含特殊字符'))
  }
}
//验证图片
const validaLogoUrl = (rule: any, value: any, callback: any) => {
  if (value) {
    callback()
  } else {
    callback(new Error('请上传图片'))
  }
}
//配置表单校验规则自定义
const rule = {
  tmName: [{ required: true, trigger: 'blur', validator: validaTname }],
  logoUrl: [{ required: true, trigger: 'blur', validator: validaLogoUrl }],
}
</script>
<style scoped lang="scss">
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.demo-pagination-block {
  margin-top: 5px;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
